package com.pet.behavior.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pet.behavior.mapper.ApReadBehaviorMapper;
import com.pet.behavior.service.ApBehaviorEntryService;
import com.pet.behavior.service.ApReadBehaviorService;
import com.pet.common.constants.MQConstants;
import com.pet.common.exception.LeadNewsException;
import com.pet.model.behavior.dtos.ReadBehaviorDto;
import com.pet.model.behavior.dtos.UpdateArticleMsg;
import com.pet.model.behavior.pojos.ApBehaviorEntry;
import com.pet.model.behavior.pojos.ApReadBehavior;
import com.pet.model.common.dtos.ResponseResult;
import com.pet.model.common.enums.AppHttpCodeEnum;
import com.pet.model.user.pojos.ApUser;
import com.pet.utils.common.JsonUtils;
import com.pet.utils.threadlocal.ThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.UUID;

/**
 * <p>
 * APP阅读行为表 服务实现类
 * </p>
 */
@Service
@Transactional
public class ApReadBehaviorServiceImpl extends ServiceImpl<ApReadBehaviorMapper, ApReadBehavior> implements ApReadBehaviorService {

    @Autowired
    private ApBehaviorEntryService apBehaviorEntryService;
    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Override
    public ResponseResult readBehavior(ReadBehaviorDto dto) {
        //1.取出登录用户信息
        ApUser apUser = (ApUser) ThreadLocalUtils.get();
        Integer userId = null;
        if(apUser!=null){
            userId = apUser.getId();
        }
        //2.取出设备信息
        Integer equipmentId = dto.getEquipmentId();
        //3.查询行为实体
        ApBehaviorEntry behaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(userId, equipmentId);
        if(behaviorEntry==null){
            throw new LeadNewsException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        try {
            //4.查询阅读记录是否存在
            QueryWrapper<ApReadBehavior> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("entry_id",behaviorEntry.getId());
            queryWrapper.eq("article_id",dto.getArticleId());
            ApReadBehavior readBehavior = getOne(queryWrapper);
            //4.1 不存在，添加阅读记录
            if(readBehavior==null){
                readBehavior=new ApReadBehavior();
                readBehavior.setEntryId(behaviorEntry.getId());
                readBehavior.setArticleId(dto.getArticleId());
                readBehavior.setCount(dto.getCount());
                readBehavior.setPercentage(dto.getPercentage());
                readBehavior.setReadDuration(dto.getReadDuration());
                readBehavior.setLoadDuration(dto.getLoadDuration());
                readBehavior.setCreatedTime(new Date());
                save(readBehavior);
            }else {
                //4.2 存在，修改阅读记录
                readBehavior.setCount(readBehavior.getCount()+1);
                readBehavior.setReadDuration(readBehavior.getReadDuration()+dto.getReadDuration());
                readBehavior.setPercentage(dto.getPercentage());
                readBehavior.setLoadDuration(dto.getLoadDuration());
                readBehavior.setUpdatedTime(new Date());
                updateById(readBehavior);
            }

            //阅读行为时发送MQ消息

            UpdateArticleMsg updateArticleMsg = new UpdateArticleMsg();
            updateArticleMsg.setType(UpdateArticleMsg.UpdateArticleType.VIEWS);
            updateArticleMsg.setArticleId(dto.getArticleId());

            kafkaTemplate.send(MQConstants.HOT_ARTICLE_INPUT_TOPIC, UUID.randomUUID().toString(), JsonUtils.toString(updateArticleMsg));


            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            throw new LeadNewsException(AppHttpCodeEnum.SERVER_ERROR);
        }
    }
}
